﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace HXDNB.DAL
{
    public class AdBLL : IDisposable
    {
        readonly Entities _e = new Entities();

        /// <summary>
        /// 查询所有广告
        /// </summary>
        public IEnumerable<Advertisement> Select()
        {
            return _e.Advertisements.ToList();
        }

        /// <summary>
        /// 查询未发布广告
        /// </summary>
        public IEnumerable<Advertisement> SelectNoReleaseAds()
        {
            return _e.Advertisements.Where(t => t.IsRelease == "N").ToList();
        }

        /// <summary>
        /// 根据ID查询广告
        /// </summary>
        public Advertisement Get(int id)
        {
            return _e.Advertisements.FirstOrDefault(t => t.Id == id);
        }

        /// <summary>
        /// 添加广告信息
        /// </summary>
        public int Add(Advertisement ad)
        {
            try
            {
                _e.Advertisements.AddObject(ad);
                _e.SaveChanges();
            }
            catch (Exception)
            {
                ad.Id = 0;
            }

            return ad.Id;
        }

        /// <summary>
        /// 修改广告信息
        /// </summary>
        public bool Edit(Advertisement ad)
        {
            try
            {
                _e.Advertisements.Attach(ad);
                _e.ObjectStateManager.ChangeObjectState(ad, EntityState.Modified);
                return _e.SaveChanges() > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除广告信息
        /// </summary>
        public bool Delete(int id)
        {
            try
            {
                var info = Get(id);
                if (info == null)
                    return false;
                _e.Advertisements.DeleteObject(info);
                return _e.SaveChanges() > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 修改广告发布状态为已发布
        /// </summary>
        public bool Publish(int id)
        {
            try
            {
                var info = Get(id);
                info.IsRelease = "Y";
                return _e.SaveChanges() > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}
